<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { marked } from "marked";
import html2canvas from "html2canvas";

// API基础URL配置，可以根据环境变量或部署环境进行调整
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:20010';

const isAnyRegionLoading = computed(() => {
    return regions.some((region) => regionStates.value[region.id].loading);
});

const refreshAllRegions = () => {
    regions.forEach((region) => {
        fetchNewsAnalysis(region.id);
    });
};

const regions = [
    { id: "china", name: "国内" },
    { id: "us", name: "美国" },
    { id: "hk", name: "香港" },
    { id: "global", name: "全球" },
];

interface RegionState {
    loading: boolean;
    error: string | null;
    analysisResult: any;
    selected: boolean;
}

const regionStates = ref<Record<string, RegionState>>(
    Object.fromEntries(
        regions.map((region) => [
            region.id,
            {
                loading: false,
                error: null,
                analysisResult: null,
                selected: false,
            },
        ])
    )
);

const isAllSelected = computed(() => {
    return regions.every((region) => regionStates.value[region.id].selected);
});

const toggleAllRegions = (event: Event) => {
    const checked = (event.target as HTMLInputElement).checked;
    regions.forEach((region) => {
        regionStates.value[region.id].selected = checked;
    });
};

const parseAnalysisContent = async (content: string) => {
    const sections: Record<string, string> = {};
    const parts = content.split(/(?=###)/);

    for (const part of parts) {
        const trimmedPart = part.trim();
        if (trimmedPart) {
            const titleMatch = trimmedPart.match(/^### (.+)/);
            if (titleMatch) {
                const title = titleMatch[1];
                const content = trimmedPart.replace(/^### .+\n/, "").trim();
                sections[title] = await marked.parse(content);
            }
        }
    }

    return sections;
};

const fetchNewsAnalysis = async (region: string) => {
    const state = regionStates.value[region];
    state.loading = true;
    state.error = null;

    try {
        const response = await fetch(
            `${API_BASE_URL}/analyze/${region}`
        );
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        state.analysisResult = {
            ...data,
            parsedAnalysis: await parseAnalysisContent(data.analysis)
        };
    } catch (e) {
        state.error = e instanceof Error ? e.message : "获取新闻分析失败";
    } finally {
        state.loading = false;
    }
};

const refreshAnalysis = (region: string) => {
    fetchNewsAnalysis(region);
};

const exportSelectedRegions = async () => {
    const selectedRegions = regions.filter(
        (region) => regionStates.value[region.id].selected
    );
    if (selectedRegions.length === 0) {
        alert("请至少选择一个市场模块进行导出");
        return;
    }

    try {
        const container = document.createElement("div");
        container.style.position = "fixed";
        container.style.left = "-9999px";
        container.style.padding = "20px";
        container.style.backgroundColor = "#ffffff";
        container.style.width = "800px";
        container.style.margin = "0";
        container.style.boxShadow = "0 8px 24px rgba(0, 0, 0, 0.12)";
        container.style.borderRadius = "16px";
        container.style.overflowY = "visible";
        container.style.height = "auto";
        container.style.maxWidth = "100%";
        container.style.display = "flex";
        container.style.flexDirection = "column";
        container.style.alignItems = "stretch";

        for (const region of selectedRegions) {
            const regionState = regionStates.value[region.id];
            if (
                !regionState.loading &&
                !regionState.error &&
                regionState.analysisResult
            ) {
                const regionElement = document.createElement("div");
                regionElement.style.marginBottom = "15px";
                regionElement.style.pageBreakInside = "avoid";
                regionElement.style.width = "100%";
                regionElement.innerHTML = `
                    <h2 style="color: #2c3e50; margin-bottom: 12px; font-size: 32px; text-align: center; border-bottom: 3px solid #eef2f7; padding-bottom: 8px;">${
                        region.name
                    }市场分析</h2>
                    ${Object.entries(
                        parseAnalysisContent(
                            regionState.analysisResult.analysis
                        )
                    )
                        .map(
                            ([title, content]) => `
                            <div style="margin-bottom: 12px; background-color: #f8fafc; padding: 15px; border-radius: 12px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);">
                                <h3 style="color: #34495e; font-size: 28px; margin-bottom: 10px; border-left: 5px solid #42b983; padding-left: 15px;">${title}</h3>
                                <div style="font-size: 24px; line-height: 1.3; color: #2c3e50; white-space: pre-wrap; text-align: justify; padding: 0 15px;">${content}</div>
                            </div>
                        `
                        )
                        .join("")}`;
                container.appendChild(regionElement);
            }
        }

        document.body.appendChild(container);

        // 等待内容完全渲染
        await new Promise((resolve) => setTimeout(resolve, 1000));

        const canvas = await html2canvas(container, {
            scale: 2,
            backgroundColor: "#ffffff",
            logging: false,
            width: 800,
            height: container.scrollHeight,
            windowWidth: 800,
            windowHeight: container.scrollHeight,
            useCORS: true,
            onclone: function (clonedDoc) {
                const elements =
                    clonedDoc.getElementsByClassName("markdown-body");
                
                for (let el of elements) {
                    const htmlElement = el as HTMLElement;
                    htmlElement.style.fontSize = "24px";
                    htmlElement.style.lineHeight = "1.3";
                    htmlElement.style.whiteSpace = "pre-wrap";
                    htmlElement.style.textAlign = "justify";
                    htmlElement.style.padding = "0 15px";
                }
            },
        });
        document.body.removeChild(container);

        const now = new Date();
        const timestamp = `${now.getFullYear()}${String(
            now.getMonth() + 1
        ).padStart(2, "0")}${String(now.getDate()).padStart(2, "0")}_${String(
            now.getHours()
        ).padStart(2, "0")}${String(now.getMinutes()).padStart(2, "0")}${String(
            now.getSeconds()
        ).padStart(2, "0")}`;
        const link = document.createElement("a");
        link.download = `市场分析_${timestamp}.png`;
        link.href = canvas.toDataURL("image/png");
        link.click();
    } catch (error) {
        console.error("导出图片时发生错误:", error);
        alert("导出图片失败，请稍后重试");
    }
};

onMounted(() => {
    regions.forEach((region) => {
        fetchNewsAnalysis(region.id);
    });
});
</script>

<template>
    <div class="news-analyzer">
        <header>
            <h1 class="main-title">财经新闻分析</h1>
            <div class="export-controls">
                <button
                    class="refresh-all-btn"
                    @click="refreshAllRegions"
                    :disabled="isAnyRegionLoading"
                >
                    <span class="btn-icon">🔄</span> 全局刷新
                </button>
                <div class="export-dropdown">
                    <button class="export-btn">
                        <span class="btn-icon">📤</span> 导出
                    </button>
                    <div class="export-menu">
                        <div class="export-menu-content">
                            <div class="export-menu-header">选择要导出的模块：</div>
                            <div class="export-menu-items">
                                <label class="export-menu-item select-all">
                                    <input
                                        type="checkbox"
                                        :checked="isAllSelected"
                                        @change="toggleAllRegions"
                                        class="region-checkbox"
                                    />
                                    <span>全部</span>
                                </label>
                                <label
                                    v-for="region in regions"
                                    :key="region.id"
                                    class="export-menu-item"
                                >
                                    <input
                                        type="checkbox"
                                        v-model="regionStates[region.id].selected"
                                        class="region-checkbox"
                                    />
                                    <span>{{ region.name }}市场</span>
                                </label>
                            </div>
                            <button
                                @click="exportSelectedRegions"
                                class="export-confirm-btn"
                            >
                                导出选中模块
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </header>
        <div class="grid-container">
            <div v-for="region in regions" :key="region.id" class="region-card">
                <div class="region-header">
                    <div class="region-title">
                        <h2>{{ region.name }}市场</h2>
                    </div>
                    <button
                        class="refresh-btn"
                        @click="refreshAnalysis(region.id)"
                        :disabled="regionStates[region.id].loading"
                    >
                        刷新
                    </button>
                </div>

                <div v-if="regionStates[region.id].error" class="error-message">
                    {{ regionStates[region.id].error }}
                </div>

                <div v-if="regionStates[region.id].loading" class="loading">
                    <div class="spinner"></div>
                    <p>正在分析新闻数据...</p>
                </div>

                <div
                    v-if="
                        !regionStates[region.id].loading &&
                        !regionStates[region.id].error &&
                        regionStates[region.id].analysisResult
                    "
                    class="content"
                >
                    <template
                        v-if="regionStates[region.id].analysisResult?.analysis"
                    >
                        <div class="analysis-sections">
                            <div
                                v-for="(section, index) in regionStates[region.id].analysisResult!.parsedAnalysis"
                                :key="index"
                                class="section"
                            >
                                <h3>{{ index }}</h3>
                                <div
                                    class="section-content markdown-body"
                                    v-html="section"
                                ></div>
                            </div>
                        </div>
                    </template>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped>
.news-analyzer {
    max-width: 1600px;
    margin: 0 auto;
    padding: 20px;
    background-color: #f5f7fa;
    min-height: 100vh;
    font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
}

header {
    background-color: white;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 25px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.btn-icon {
    margin-right: 5px;
}

.main-title {
    text-align: center;
    margin: 20px 0 30px;
    color: #2c3e50;
    font-size: 2.2em;
    font-weight: 600;
    text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
}

.export-controls {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-bottom: 20px;
    padding: 0 20px;
    position: relative;
}

.export-dropdown {
    position: relative;
    display: inline-block;
}

.export-btn {
    padding: 10px 20px;
    background-color: #42b983;
    color: white;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: 1em;
    transition: all 0.3s ease;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.export-btn:hover {
    background-color: #3aa876;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.export-menu {
    display: none;
    position: absolute;
    right: 0;
    top: 100%;
    margin-top: 5px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
    z-index: 1000;
    min-width: 220px;
    animation: fadeIn 0.2s ease-out;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(-10px); }
    to { opacity: 1; transform: translateY(0); }
}

.export-dropdown:hover .export-menu {
    display: block;
}

.export-menu-content {
    padding: 15px;
}

.export-menu-header {
    font-size: 0.95em;
    color: #555;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid #eee;
    font-weight: 500;
}

.export-menu-items {
    display: flex;
    flex-direction: column;
    gap: 10px;
    margin-bottom: 15px;
}

.export-menu-item {
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 0.95em;
    color: #333;
    cursor: pointer;
    padding: 6px 0;
    transition: all 0.2s;
}

.export-menu-item:hover {
    color: #42b983;
}

.export-confirm-btn {
    width: 100%;
    padding: 10px;
    background-color: #42b983;
    color: white;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: 0.95em;
    transition: all 0.3s ease;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.export-confirm-btn:hover {
    background-color: #3aa876;
    box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.region-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    position: relative;
    padding-bottom: 10px;
    border-bottom: 1px solid #eef2f7;
}

.region-title {
    display: flex;
    align-items: center;
}

.region-header h2 {
    margin: 0;
    color: #2c3e50;
    font-size: 1.5em;
    font-weight: 600;
}

.refresh-btn {
    padding: 8px 16px;
    border: none;
    border-radius: 6px;
    background-color: #4a90e2;
    color: white;
    cursor: pointer;
    font-size: 0.95em;
    transition: all 0.3s ease;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    display: flex;
    align-items: center;
    justify-content: center;
}

.refresh-btn::before {
    content: "🔄";
    margin-right: 5px;
    font-size: 0.9em;
}

.refresh-btn:hover {
    background-color: #357abd;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.refresh-btn:disabled {
    background-color: #a0a0a0;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
}

.section-content {
    font-size: 0.95em;
    line-height: 1.6;
    text-align: left;
}

.grid-container {
    margin-bottom: 20px;
    display: flex;
    flex-direction: column;
    gap: 25px;
}

.region-card {
    background-color: white;
    border-radius: 12px;
    padding: 28px;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.region-card::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 4px;
    background: linear-gradient(90deg, #42b983, #4a90e2);
}

.region-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
}

.analysis-sections {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
}

.section {
    background-color: #f8fafc;
    padding: 22px;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
    border: 1px solid rgba(0, 0, 0, 0.03);
}

.section:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.section h3 {
    color: #34495e;
    margin-bottom: 16px;
    font-size: 1.3em;
    border-left: 4px solid #42b983;
    padding-left: 12px;
    font-weight: 600;
    display: flex;
    align-items: center;
}

.section h3::before {
    content: "📊";
    margin-right: 8px;
    font-size: 1.1em;
}

.section-content {
    font-size: 0.95em;
    line-height: 1.7;
    color: #3c4858;
}

.section-content p {
    margin-bottom: 12px;
}

.section-content ul, .section-content ol {
    padding-left: 20px;
    margin-bottom: 12px;
}

.section-content strong {
    color: #2c3e50;
    font-weight: 600;
}

.select-all {
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
    margin-bottom: 10px;
    font-weight: 500;
}

.refresh-all-btn {
    margin-right: 10px;
    padding: 10px 20px;
    background-color: #4caf50;
    color: white;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: 0.95em;
    transition: all 0.3s ease;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.refresh-all-btn:hover {
    background-color: #45a049;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.refresh-all-btn:disabled {
    background-color: #cccccc;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
}

/* 添加加载动画样式 */
.loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 0;
}

.spinner {
    width: 40px;
    height: 40px;
    border: 4px solid rgba(66, 185, 131, 0.2);
    border-radius: 50%;
    border-top-color: #42b983;
    animation: spin 1s linear infinite;
    margin-bottom: 15px;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}

.error-message {
    color: #e74c3c;
    padding: 20px;
    text-align: center;
    background-color: #fef2f2;
    border-radius: 8px;
    margin: 20px 0;
    border-left: 4px solid #e74c3c;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.error-message::before {
    content: "⚠️";
    font-size: 2em;
    margin-bottom: 10px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
    .analysis-sections {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 768px) {
    .news-analyzer {
        padding: 15px;
    }
    
    .main-title {
        font-size: 1.8em;
        margin: 15px 0 20px;
    }
    
    .export-controls {
        flex-direction: column;
        align-items: flex-end;
        gap: 10px;
    }
    
    .region-card {
        padding: 20px;
    }
    
    .section {
        padding: 15px;
    }
    
    .section h3 {
        font-size: 1.1em;
    }
}

@media (max-width: 480px) {
    .main-title {
        font-size: 1.5em;
    }
    
    .export-btn, .refresh-all-btn, .refresh-btn {
        padding: 8px 12px;
        font-size: 0.9em;
    }
    
    .region-header h2 {
        font-size: 1.3em;
    }
}
</style>
